package com.laboratory.Process;

import org.apache.logging.log4j.LogManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 第二种方法：使用 Callable<V> 和 FutureTask<V>
 * @author admin
 *
 */
public class CallableTest {

	private static org.apache.logging.log4j.Logger logger= LogManager.getLogger(CallableTest.class);
	
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis(); 
		List<FutureTask<Integer>> futureTasks = new ArrayList<>(10);
		 // 新建 10 个线程，每个线程分别负责累加 1~10, 11~20, ..., 91~100
		for(int i =0; i<10; i++){
			AccumCallable accumCallable = new CallableTest().new AccumCallable(i*10+1, (i+1)*10);
			FutureTask<Integer> task = new FutureTask<>(accumCallable);
			futureTasks.add(task);
			
			Thread worker = new Thread(task, "慢速累加器线程" + i);
            worker.start();			
		}
		
		int total = 0;
		for(FutureTask<Integer> futureTask:futureTasks){
			try {
				total += futureTask.get();
			} catch (InterruptedException | ExecutionException e) {				
				e.printStackTrace();
			}
		}
		logger.info(Thread.currentThread().getName() + " - 运行结束，结果为 "+ total +", 运行时间为" + (System.currentTimeMillis()-startTime) );
	}
	
	
	//这是一个做累加计算的线程
	class AccumCallable implements Callable<Integer>{

        private final int begin;
        private final int end;

        public AccumCallable(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }
        
		@Override
		public Integer call() throws Exception {
			long startTime = System.currentTimeMillis(); 
			 int result = 0;
			 for(int i = begin; i<= end; i++){
				 result += i;
			 }
			 Thread.sleep(2000);
			logger.info(Thread.currentThread().getName() + " - 运行结束，结果为 "+ result +", 运行时间为" + (System.currentTimeMillis()-startTime) );

			return result;
		}
		
	}

}
